using DiLu.Expansion.File.Operates.Minio.Configs;
using DiLu.Expansion.File.Operates.Minio.Tools;
using Minio.DataModel.Args;

namespace DiLu.Expansion.File.Operates.Minio;

public static class SaveMinioFile
{
    /// <summary>
    ///     保存文件流到FTP
    /// </summary>
    /// <param name="config">文件流保存到FTP配置</param>
    /// <returns></returns>
    public static async Task<string> SaveAsync(this SaveFileStreamToMinioConfig config)
    {
        //创建桶
        await config.MinioClient.CreateBucketAsync(config.BucketName);
        //文件完整路径
        string fileFullPath;
        //文件相对路径
        string fileRelativePath;
        //文件是否存在
        bool fileExists;
        do
        {
            //保存时间
            var nowTime = DateTime.Now;
            //新文件名称
            var newFileName = $"{nowTime:yyyyMMddHHmmssfffff}{config.FileExtension}";
            //相对目录
            var relativeDirectory = Path.Combine($"{nowTime:yyyy}", $"{nowTime:MM}", $"{nowTime:dd}");
            //完整目录
            var fullDirectory = Path.Combine(config.RootDirectory, config.FileGroupName, relativeDirectory);
            fileFullPath = Path.Combine(fullDirectory, newFileName);
            fileRelativePath = Path.Combine(relativeDirectory, newFileName);
            fileExists = await config.MinioClient.FileExistsAsync(config.BucketName, newFileName);
            await Task.Delay(0);
        } while (fileExists);

        var contentType = MimeTypes.GetMimeType(fileFullPath);
        var putObjectArgs = new PutObjectArgs()
            .WithBucket(config.BucketName)
            .WithObject(fileFullPath)
            .WithStreamData(config.FileStream)
            .WithObjectSize(config.FileStream.Length)
            .WithContentType(contentType);
        await config.MinioClient.PutObjectAsync(putObjectArgs);

        return fileRelativePath;
    }
}